import styled from 'styled-components';
import React from 'react';

const ctx = React.createContext({});
interface IProps {
  user: {
    name: string;
    age: number
  },
  callback: (arg: any) => void
}

function Child1(props: IProps) {
    const {user,callback} = props;
    const res = useContext(ctx);
    console.log('res',res)
    const style = {
        width: '180px',
        height: '300px',
        padding: '10px',
        backgroundColor: 'skyblue'
    };
    const event: any = new Event('setData'); // 自定义事件，添加到事件中心
    const handleSetdata = () => {
        event.params = 111;
        console.log(event);
        window.dispatchEvent(event); // 派发事件
    }
    const obj = {
        a: 1
    }
  return (
    <div style={style}>
      <h3>子组件1</h3>  
      <h3>姓名：{user.name}</h3>
      <h3>年龄：{user.age}</h3>
      <h3>ctx接收到的数据：
        {/* JSX或者TSX不可以直接渲染对象，只能渲染基本数据类型（字符串、数字、布尔值）或 React 元素 */}
        {res ? JSON.stringify(res) : '暂无数据'} 
      </h3>
      <button onClick={()=>{
        callback('hh');
      }}>改变名字</button>
      <button onClick={handleSetdata}>向兄弟组件传数据</button>
    </div>
  );
}
function Child2() {
    const style = {
        width: '180px',
        height: '180px',
        padding: '10px',
        backgroundColor: 'orange',
        marginTop: '20px'
    };
    const [num,setNum] = useState(0); 
    window.addEventListener('setData',(e: any)=>{
       setNum(e.params);
    })
  return (
    <div style={style}>
      <h3>子组件2</h3> 
      <h3>接收到的兄弟组件数据为：{num}</h3>
      <h3>ctx接收到的数据：
         
      </h3>
    </div>
  );
}

export default function communicationComp() {
  const [user, setUser] = useState({
    name: 'aa',
    age: 18
  });
  const handleChangeName = (name:string) => {
    console.log('改变名字了',name);
    setUser({
        ...user,
        name
    });
  }
  return (
    <Wrapper>
      <div className="communicationComp">
        <ctx.Provider value={{a: 12,b: 22}}>
            <Child1 user={user} callback={handleChangeName} />
            <Child2 />    
        </ctx.Provider>
      </div>
    </Wrapper>
  );
}
const Wrapper = styled.div`
  .communicationComp {
    color: #000;
    padding: 10px;
  }
  .communicationComp h3 {
    margin: 10px 0;
  }  
`;
